package com.detroitchow.tasks;

/** 
 * Query detroitchow for list of all available stores
 */

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.detroitchow.DetroitChowUtils;
import com.detroitchow.IFetchStoresObserver;
import com.detroitchow.LogUtil;
import com.detroitchow.StoreTagVO;
import com.detroitchow.StoreVO;
import com.detroitchow.TagCollection;
import com.detroitchow.sqlite.DatabaseAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.os.AsyncTask;

public class FetchAllStoresTask extends AsyncTask<Void, Void, ArrayList<TagCollection>> {
	private final String GET_STORES_URL="http://detroitchow.com/getStoreList.php?v=1";
  private final String GET_TAGS_URL="http://detroitchow.com/GetStoreTags.php?v=1";
  private IFetchStoresObserver observer;
  //ArrayList<com.detroitchow.StoreVO> result=null;
  DatabaseAdapter dbAdapter;
  
  public FetchAllStoresTask(IFetchStoresObserver arg) {
	  // TODO Auto-generated constructor stub
  	observer = arg;
  }

  public void setDatabaseAdapter(DatabaseAdapter arg) {
  	dbAdapter = arg;
  	
  }
  
  @Override
  protected void onPostExecute(ArrayList<TagCollection> arg) {
    // TODO Auto-generated method stub
    super.onPostExecute(arg);
    observer.notifyFetchAllStoresComplete(arg);
  }
  @Override
  protected ArrayList<TagCollection> doInBackground(Void... arg0) {
    ArrayList<com.detroitchow.StoreVO> allStores=null;
    ArrayList<com.detroitchow.StoreTagVO> tags=null;
    String requestContent;
    HttpClient httpclient = new DefaultHttpClient();  
    HttpGet request = new HttpGet(GET_STORES_URL);
    ResponseHandler<String> handler = new BasicResponseHandler();
    Gson gson = new Gson();
    Type resultType = new TypeToken<ArrayList<StoreVO>>(){}.getType();
    
    try {
    	//LogUtil.logTimer("FetchAllStortesTask.doInBackground before Http Call", Calendar.getInstance());
      requestContent = httpclient.execute(request, handler);  
      allStores = gson.fromJson(requestContent, resultType);
      //LogUtil.logTimer("FetchAllStortesTask.doInBackground after Http Call", Calendar.getInstance());
      
       
    }catch(Exception e){
    	LogUtil.log("DetroitChowRemoteObjectManager", e.getMessage());
    }
    
    httpclient.getConnectionManager().shutdown();
    ArrayList<TagCollection> result=null;
    if(allStores == null)
    	;
    else {
    	LogUtil.log("FetchAllStoresTask", "allStores size: " + allStores.size());
    	result = DetroitChowUtils.buildMasterList(allStores);
    }
    
    return result;
  }

}
